/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package cz.muni.fi.pv168.reminder.swing.workers;

import cz.muni.fi.pv168.reminder.entities.Task;
import cz.muni.fi.pv168.reminder.entities.Worker;
import cz.muni.fi.pv168.reminder.managers.AssignmentManager;
import cz.muni.fi.pv168.reminder.managers.implementation.AssignmentManagerImpl;
import cz.muni.fi.pv168.reminder.swing.FrameMainWindow;
import java.util.List;
import javax.swing.SwingWorker;

/**
 *
 * @author Adic
 */
public class AssignWorkersSwingWorker extends SwingWorker<Class<Void>, Void>{
    private Task task;
    private List<Worker> workers;
    
    public AssignWorkersSwingWorker(Task returnedTask, List<Worker> workers) {
        task = returnedTask;
        this.workers = workers;
    }

    @Override
    protected Class<Void> doInBackground() throws Exception {
        AssignmentManager assignmentManager = new AssignmentManagerImpl();
        assignmentManager.setDataSource(FrameMainWindow.getDataSource());
        List<Worker> assignedWorkers = assignmentManager.findWorkersOfTask(task);
        
        if(assignedWorkers == null){
            for(Worker worker : workers){
                assignmentManager.assignTaskToWorker(task, worker);
            }
        }else{
            for(Worker worker : workers){
                if(!assignedWorkers.contains(worker)){
                    assignmentManager.assignTaskToWorker(task, worker);
                }else{
                    assignedWorkers.remove(worker);
                }
            }
            for(Worker worker : assignedWorkers){
                assignmentManager.removeTaskFromWorker(task, worker);
            }
        }
        
        return Void.class;
    }    
}
